package com.asr.controller;

import com.asr.dto.CreateTaskRequest;
import com.asr.model.ApiResponse;
import com.asr.model.AsrTask;
import com.asr.service.AsrTaskService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/asr")
@RequiredArgsConstructor
public class AsrController {
    
    private final AsrTaskService asrTaskService;
    
    /**
     * 创建 ASR 任务
     */
    @PostMapping("/tasks")
    public ApiResponse<AsrTask> createTask(@Valid @RequestBody CreateTaskRequest request) {
        try {
            log.info("收到创建任务请求，音频文件数: {}", request.getAudioFiles().size());
            log.debug("任务配置: {}", request.getConfig());
            
            AsrTask task = asrTaskService.createTask(
                request.getAudioFiles(),
                request.getConfig(),
                request.getOutputDir()
            );
            
            // 异步执行任务
            asrTaskService.executeTask(task.getTaskId());
            
            return ApiResponse.success("任务创建成功", task);
        } catch (Exception e) {
            log.error("创建任务失败", e);
            return ApiResponse.error("创建任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取任务详情
     */
    @GetMapping("/tasks/{taskId}")
    public ApiResponse<AsrTask> getTask(@PathVariable String taskId) {
        AsrTask task = asrTaskService.getTask(taskId);
        if (task == null) {
            return ApiResponse.error(404, "任务不存在");
        }
        return ApiResponse.success(task);
    }
    
    /**
     * 获取所有任务
     */
    @GetMapping("/tasks")
    public ApiResponse<List<AsrTask>> getAllTasks() {
        List<AsrTask> tasks = asrTaskService.getAllTasks();
        return ApiResponse.success(tasks);
    }
    
    /**
     * 取消任务
     */
    @PostMapping("/tasks/{taskId}/cancel")
    public ApiResponse<Void> cancelTask(@PathVariable String taskId) {
        boolean success = asrTaskService.cancelTask(taskId);
        if (success) {
            return ApiResponse.success("任务已取消", null);
        } else {
            return ApiResponse.error("取消任务失败");
        }
    }
    
    /**
     * 删除任务
     */
    @DeleteMapping("/tasks/{taskId}")
    public ApiResponse<Void> deleteTask(@PathVariable String taskId) {
        boolean success = asrTaskService.deleteTask(taskId);
        if (success) {
            return ApiResponse.success("任务已删除", null);
        } else {
            return ApiResponse.error("删除任务失败");
        }
    }
}
